use std::collections::HashMap;

use actix_web::HttpRequest;
use urlencoding::decode;

#[derive(Debug)]
pub struct WebParam {
    param: HashMap<String, String>,
}

impl WebParam {
    ///构造函数
    pub fn new() -> Self {
        WebParam {
            param: HashMap::new(),
        }
    }
    ///构造函数，传args
    pub fn new_with_args(args: &HashMap<String, String>) -> Self {
        WebParam {
            param: args.clone(),
        }
    }
    ///设置字符串参数
    pub fn set_str(&mut self, key: &str, value: &str) {
        self.param.insert(key.to_string(), value.to_string());
    }
    ///设置bool类型的参数
    pub fn set_bool(&mut self, key: &str, value: bool) {
        self.param.insert(key.to_string(), value.to_string());
    }
    ///获取字符串参数，返回Option类型
    pub fn get_str(&self, key: &str) -> Option<&String> {
        self.param.get(key)
    }
    ///获取bool类型的参数
    pub fn get_bool(&self, key: &str) -> bool {
        self.param.get(key).map(|v| v == "true").unwrap_or_else(|| false)
    }
}

pub fn web_param(req: &HttpRequest) -> WebParam {
    let mut r = WebParam::new();
    let list = req.query_string().split("&").map(String::from).collect::<Vec<String>>();
    for x in list {
        let split = x.split("=").map(String::from).collect::<Vec<String>>();
        match split.len() {
            1 => {
                let key = &split[0];
                let key = decode(key).unwrap().to_string();
                let key = key.as_str();
                r.set_bool(key, true)
            }
            2 => {
                let key = &split[0];
                let value = &split[1];
                let key = decode(key).unwrap().to_string();
                let key = key.as_str();
                let value = decode(value).unwrap().to_string();
                let value = value.as_str();
                r.set_str(key, value);
            }
            _ => {}
        }
    }
    r
}
